package com.test.socket;

import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.FileChannel;
import java.nio.channels.Pipe;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;

public class MySocket {

  public static void main(String[] args) {
    try {
      // 创建一个管道
      Pipe pipe=Pipe.open();
      final SinkChannel sink=pipe.sink();
      final SourceChannel source=pipe.source();
      Thread writeT=new Thread() {

        @Override
        public void run() {
          try {
            // 向管道中写数据
            sink.write(ByteBuffer.wrap("123".getBytes("utf-8")));
          } catch(UnsupportedEncodingException e) {
            e.printStackTrace();
          } catch(IOException e) {
            e.printStackTrace();
          }
        }
      };
      Thread readT=new Thread() {

        @Override
        public void run() {
          ByteBuffer buffer=ByteBuffer.allocate(2048);
          try {
            // 从管道中读数据
            source.read(buffer);
            buffer.flip();
            if(buffer.hasRemaining()) {
              byte[] b=new byte[buffer.limit()];
              buffer.get(b);
              String s=new String(b, "utf-8");
              System.out.println(s);
            }
          } catch(IOException e) {
            e.printStackTrace();
          }
        }
      };
      writeT.start();
      readT.start();
    } catch(IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    try {
      // 客户端通道
      SocketChannel sc=SocketChannel.open();
      sc.connect(new InetSocketAddress("localhost", 10000));
      // 服务器通道
      ServerSocketChannel ssc=ServerSocketChannel.open();
      ServerSocket ss=ssc.socket();
      ss.bind(new InetSocketAddress(10000));
      // 数据报通道
      @SuppressWarnings("unused")
      DatagramChannel dc=DatagramChannel.open();
      // 文件
      RandomAccessFile raf=new RandomAccessFile("somFile", "r");
      @SuppressWarnings("unused")
      FileChannel fc=raf.getChannel();
    } catch(IOException e) {
      e.printStackTrace();
    }
  }
}
